<template>
  <TopNavBar :title="_t18('25_pledge_order_record')" @rightClick="handleRightClick" type="back" />
  <div class="order-detail-page">
    <div class="order-tabs">
      <div :class="['tab', { active: activeTab === 'current' }]" @click="selectActive('current')">
        {{ _t18('25_current_position') }}
      </div>
      <div :class="['tab', { active: activeTab === 'history' }]" @click="selectActive('history')">
        {{ _t18('25_rxce_exchange_hisentrust') }}
      </div>
    </div>

    <!-- 当前持仓 -->
    <div v-if="activeTab === 'current'">
      <div v-if="currentOrders.length === 0" class="empty-box">
        <img class="empty-icon" src="/static/img/W2k_c7838bd9_spH.cd0c5744.png" alt="empty" />
        <div class="empty-text">{{ _t18('25_wushuju') }}</div>
      </div>
      <div v-else>
        <div v-for="(order, idx) in currentOrders" :key="idx" class="order-card current">
          <div class="order-card-header">
            <div class="pair-info">
              <div class="pair">{{ (order.symbol || '').toUpperCase() }}/USD</div>
              <div class="order-id">#{{ order.orderNo }}</div>
            </div>
          
            <div class="leverage-info">
              <span
                class="status"
                :class="order.type == 0 ? 'up' : 'down'"
              >
                {{ order.type == 0 ? _t18('25_kaiduo') : _t18('25_kaikong') }}
              </span>
              <span class="leverage-badge">{{ order.leverage }}X</span>
            </div>
          </div>

          <div class="order-card-body">
            <div class="row"><span class="label">{{ _t18('25_open_time') }}</span><span class="value">{{ order.createTime }}</span></div>
            <div class="row"><span class="label">{{ _t18('25_open_avg_price') }}</span><span class="value">{{ order.openPrice }} </span></div>
            <div class="row"><span class="label">{{ _t18('25_position_quantity') }}</span><span class="value">{{ order.openNum }} </span></div>
            <div class="row"><span class="label">{{ _t18('25_liquidation_price') }}</span><span class="value">{{ order.closePrice }} </span></div>
            <div class="row"><span class="label">{{ _t18('25_margin') }}</span><span class="value">{{ order.amount }} </span></div>
            <div class="row"><span class="label">{{ _t18('25_fee') }}</span><span class="value">{{ order.openFee }}</span></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 历史订单 -->
    <div v-if="activeTab === 'history'">
      <div v-if="historyOrders.length === 0" class="empty-box">
        <img class="empty-icon" src="/static/img/W2k_c7838bd9_spH.cd0c5744.png" alt="empty" />
        <div class="empty-text">{{ _t18('25_wushuju') }}</div>
      </div>
      <div v-else>
        <div v-for="(order, idx) in historyOrders" :key="idx" class="order-card history">
          <div class="order-card-header">
            <div class="pair-info">
              <div class="pair">
                {{ (order.symbol || '').toUpperCase() }}/USD
                <span class="tag up" v-if="order.type == 0">
                  {{ _t18('25_open_short') }} <span class="leverage-badge">{{ order.leverage }}X</span>
                </span>
                <span class="tag down" v-if="order.type == 1">
                  {{ _t18('25_open_long') }} <span class="leverage-badge">{{ order.leverage }}X</span>
                </span>
              </div>

              <div class="order-id">#{{ order.orderNo }}</div>
            </div>

            <!-- 状态 -->
            <span class="status done">{{ _t18('25_closed') }}</span>
          </div>

          <div class="order-card-body">
            <div class="row"><span class="label">{{ _t18('25_open_time') }}</span><span class="value">{{ order.createTime }}</span></div>
            <div class="row"><span class="label">{{ _t18('25_deal_time') }}</span><span class="value">{{ order.dealTime }}</span></div>
            <div class="row"><span class="label">{{ _t18('25_open_avg_price') }}</span><span class="value">{{ order.openPrice }} </span></div>
            <div class="row"><span class="label">{{ _t18('25_deal_avg_price') }}</span><span class="value">{{ order.dealPrice }} </span></div>
            <div class="row"><span class="label">{{ _t18('25_deal_quantity') }}</span><span class="value">{{ order.dealNum }} </span></div>
            <div class="row">
              <span class="label">{{ _t18('25_earnings') }}</span>
              <span
                class="value"
                :class="{
                  profit: Number(order.earn) > 0,
                  loss: Number(order.earn) < 0
                }"
              >
                {{ order.earn }} 
              </span>
            </div>
            <div class="row"><span class="label">{{ _t18('25_fee') }}</span><span class="value">{{ order.sellFee }}</span></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { orderList, contractHistoryList } from '@/api/trade/index'



const router = useRouter()
const activeTab = ref('current')
const currentOrders = ref([])
const historyOrders = ref([])

function formatTime(value) {
  if (!value) return '-'

  const date = new Date(value)
  if (isNaN(date.getTime())) return value

  const yyyy = date.getFullYear()
  const MM = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')

  let hours = date.getHours()
  const ampm = hours >= 12 ? 'PM' : 'AM'
  hours = hours % 12 || 12 // 0点显示为12

  const hh = String(hours).padStart(2, '0')
  const mm = String(date.getMinutes()).padStart(2, '0')
  const ss = String(date.getSeconds()).padStart(2, '0')

  return `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss} ${ampm}`
}




const pageNum = ref(10)
const pageSize = ref(1)

const getList = async (status) => {
  try {
    const data = {
      status, // ✅ 动态传入状态：0=持仓中，1=历史订单
      pageSize: pageSize.value,
      pageNum: pageNum.value
    }

    const res = await contractHistoryList(data)

    if (res.code === 200 && Array.isArray(res.rows)) {
      const list = res.rows.map(i => ({
        ...i,
        status: Number(i.status ?? 0),
        createTime: formatTime(i.createTime),
        closeTime: formatTime(i.closeTime),
        dealTime: formatTime(i.dealTime) // ✅ 新增：格式化成交时间
      }))

      if (status === 0) currentOrders.value = list
      if (status === 1) historyOrders.value = list
    }
  } catch (e) {
    console.error('加载订单列表失败', e)
  }
}


function selectActive(val) {
  activeTab.value = val
  getList(val === 'current' ? 0 : 1)
}

function goToDetail(id) {
  router.push({ path: '/quantContractOrderDetail', query: { id } })
}

onMounted(() => getList(0))
</script>

<style scoped>
.order-detail-page {
  background: #f7f8fa;
  min-height: 100vh;
  padding: 24px 0 0 0;
}

.order-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  border-radius: 999px;
  margin: 0 auto 32px auto;
  width: 90%;
  max-width: 380px;
  height: 52px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 4px;
}
.tab {
  flex: 1;
  text-align: center;
  font-size: 14px;
  font-weight: 600;
  padding: 10px 0;
  border-radius: 999px;
  color: #333;
  cursor: pointer;
  transition: all 0.25s ease;
}
.tab.active {
  background: #000;
  color: #fff;
  font-weight: 700;
}

.order-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px 18px 16px 18px;
  margin: 0 auto 16px auto;
  width: 90%;
  max-width: 380px;
}

.order-card-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 12px;
  padding-bottom: 6px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.order-card-header .pair {
  font-size: 16px;
  font-weight: 700;
  color: #111;
}

.order-card-header .status {
  margin-left: auto;
  font-size: 14px;
  font-weight: 700;
  color: #00c693;
}
.order-card-header .status.pending {
  color: #ffaa00;
}
.order-card-header .status.cancel {
  color: #999;
}

.order-card-body {
  display: flex;
  flex-direction: column;
  gap: 6px;
  line-height: 1.6;
}
.row {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}
.label {
  color: #666;
}
.value {
  color: #222;
  font-weight: 600;
}
.value.profit {
  color: #00c693;
  font-weight: 700;
}
.value.loss {
  color: #fa190c;
  font-weight: 700;
}
.value.waiting {
  color: #999;
  font-weight: 500;
}

.detail-btn {
  display: block;
  width: 90%;
  margin: 16px auto 0 auto;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 24px;
  font-size: 14px;
  font-weight: 600;
  padding: 10px 0;
}
.detail-btn:hover {
  background: #222;
}

.empty-box {
  margin: 100px auto 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.empty-icon {
  width: 110px;
  height: 110px;
  margin-bottom: 20px;
}
.empty-text {
  font-size: 14px;
  color: #889;
}

/* ======================================
   币种 + 编号布局
====================================== */
.pair-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.pair-info .pair {
  font-size: 16px;
  font-weight: 700;
  color: #111;
  display: inline-flex;
  align-items: center;
  gap: 4px; /* ✅ 控制币种与文字标签间距 */
}
.pair-info .order-id {
  font-size: 12px;
  color: #999;
  font-weight: 500;
}

/* 开多 / 开空 — 改为纯文字红绿显示 */
.pair .tag {
  margin: 0 !important;
  padding: 0;
  height: auto;
  line-height: 1;
  border-radius: 0;
  font-size: 13px;
  font-weight: 700;
  background: none !important;
  box-shadow: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  vertical-align: middle;
  transform: translateY(-1px);
}

/* 🔴 开空  🟢 开多 */
.tag.up {
  color: #fa190c !important;
}
.tag.down {
  color: #00c693 !important;
}

.arrow {
  font-size: 13px;
  font-weight: 700;
  display: none; /* 去掉箭头符号 */
}
/* 黑底白字倍数徽章 */
.leverage-badge {
  background: #000;
  color: #fff;
  padding: 1px 6px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  line-height: 1.2;
  margin-left: 4px; /* 开多 / 开空 与 倍数的间距 */
  display: inline-block;
  vertical-align: middle;
}
/* 状态样式 */
.status.done {
  color: #999 !important;   /* 灰色字体 */
  font-weight: 600;
}
/* 收益颜色区分 */
.value.profit {
  color: #00c693 !important; /* 绿色：正收益 */
  font-weight: 700;
}
.value.loss {
  color: #fa190c !important; /* 红色：负收益 */
  font-weight: 700;
}


</style>
